package middleware

import (
	"fmt"
	"net/http"
	"zerorpc/app/gfzero/api/internal/config"
	"zerorpc/util/jwt"
)

type AuthInterceptorMiddleware struct {
}

func NewAuthInterceptorMiddleware() *AuthInterceptorMiddleware {
	return &AuthInterceptorMiddleware{}
}

// Handle jwt处理
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		authRequest := r.Header.Get("Authorization")
		if authRequest == "" {
			w.WriteHeader(http.StatusAccepted)
			w.Write([]byte("请登录"))
			return
		}
		// Token解密
		authParse, authErr := jwt.ParseToken(authRequest, []byte(config.GlobalConfig.JwtAuth.AccessSecret))
		// 解密失败
		if authErr != nil {
			w.WriteHeader(http.StatusAccepted)
			w.Write([]byte(authErr.Error()))
		}
		fmt.Println(authParse.Id)
		//// 初始化redis
		//redis := redisClient.Init(config.GlobalConfig)
		//val, redisErr := redis.Get(authParse.UserId).Result()
		//if redisErr != nil {
		//    w.WriteHeader(http.StatusAccepted)
		//    w.Write([]byte(redisErr.Error()))
		//    return
		//}
		//// 查看redis中是否存在该用户id
		//if val != "" {
		//    // 将用户id作为key，token做为value 重新存入redis   延长该用户token过期时长
		//    redis.Set(val, authRequest, time.Duration(config.GlobalConfig.JwtAuth.AccessExpire))
		//} else {
		//    w.WriteHeader(http.StatusAccepted)
		//    w.Write([]byte("token已过期"))
		//    return
		//}
		next(w, r)
	}
}
